package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.behavior.service.ApArticleRelationService;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.behavior.service.ApUnLikesBehaviorService;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jt
 * @date 2021/4/24 14:33
 */
@Service
public class ApArticleRelationServiceImpl implements ApArticleRelationService {

    @Resource
    private ApBehaviorEntryService apBehaviorEntryService;

    @Resource
    private ApLikesBehaviorService apLikesBehaviorService;

    @Resource
    private ApUnLikesBehaviorService apUnLikesBehaviorService;

    @Override
    public Map findApArticleRelation(ApArticleRelationDto dto) {
        Map result = new HashMap();
        boolean islike = false , isunlike = false;
        result.put("islike",islike);
        result.put("isunlike",isunlike);
//        1. 校验参数
        if (dto.getArticleId() == null || dto.getEntryId() == null) {
            return result;
        }
        if (dto.getType() != 0 && dto.getType() != 1) {
            return result;
        }
//        2. 根据参数查询用户的行为实体
        ApBehaviorEntry apBehaviorEntry;
        if (dto.getType() == 0) {
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null,dto.getEntryId());
        } else {
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getEntryId(),null);
        }
        if (apBehaviorEntry == null) {
            return result;
        }
        result.put("entryId",apBehaviorEntry.getId());
//        3. 根据实体查询是否点赞
        ApLikesBehavior likesBehavior = apLikesBehaviorService.getOne(Wrappers.<ApLikesBehavior>lambdaQuery()
                .eq(ApLikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApLikesBehavior::getEntryId, apBehaviorEntry.getId()));
        if (likesBehavior != null && likesBehavior.getOperation().intValue() == 0) {
            result.put("islike",true);
        }
//        4. 根据实体 查询是否不喜欢
        ApUnlikesBehavior unlikesBehavior = apUnLikesBehaviorService.getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()));
        if (unlikesBehavior != null && unlikesBehavior.getType().intValue() == 0) {
            result.put("isunlike",true);
        }
//        5. 封装结果返回 是否点赞 是否不喜欢 行为实体id
        return result;
    }

}
